<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');


class home extends MY_Controller {
	/**
	 * Evita la validacion (enfocado cuando se usa ajax). Ver mas en privilegios_model
	 * @var unknown_type
	 */
	private $excepcion_privilegio = array('');

	public function _remap($method){
		$this->carabiner->css(array(
				array('bootstrap/bootstrap-simplex.css', 'screen'),
				array('bootstrap/bootstrap-responsive.css', 'screen'),
				array('bootstrap/charisma-app.css', 'screen'),
				array('bootstrap/jquery-ui-1.8.21.custom.css', 'screen'),
				array('bootstrap/fullcalendar.css', 'screen'),
				array('bootstrap/fullcalendar.print.css', 'print'),
				array('bootstrap/chosen.css', 'screen'),
				array('bootstrap/uniform.default.css', 'screen'),
				array('bootstrap/colorbox.css', 'screen'),
				array('bootstrap/jquery.cleditor.css', 'screen'),
				array('bootstrap/jquery.noty.css', 'screen'),
				array('bootstrap/noty_theme_default.css', 'screen'),
				array('bootstrap/elfinder.min.css', 'screen'),
				array('bootstrap/elfinder.theme.css', 'screen'),
				array('bootstrap/jquery.iphone.toggle.css', 'screen'),
				array('bootstrap/opa-icons.css', 'screen'),
				array('bootstrap/uploadify.css', 'screen'),

				array('base-panel.css', 'screen')
		));
		$this->carabiner->js(array(
				array('bootstrap/jquery-1.7.2.min.js'),
				array('bootstrap/jquery-ui-1.8.21.custom.min.js'),
				array('bootstrap/bootstrap-transition.js'),
				array('bootstrap/bootstrap-alert.js'),
				array('bootstrap/bootstrap-modal.js'),
				array('bootstrap/bootstrap-dropdown.js'),
				array('bootstrap/bootstrap-scrollspy.js'),
				array('bootstrap/bootstrap-tab.js'),
				array('bootstrap/bootstrap-tooltip.js'),
				array('bootstrap/bootstrap-popover.js'),
				array('bootstrap/bootstrap-button.js'),
				array('bootstrap/bootstrap-collapse.js'),
				array('bootstrap/bootstrap-carousel.js'),
				array('bootstrap/bootstrap-typeahead.js'),
				array('bootstrap/bootstrap-tour.js'),
				array('bootstrap/jquery.cookie.js'),
				array('bootstrap/fullcalendar.min.js'),
				array('bootstrap/jquery.dataTables.min.js'),
				/** chart libraries **/
				array('bootstrap/excanvas.js'),
				array('bootstrap/jquery.flot.min.js'),
				array('bootstrap/jquery.flot.pie.min.js'),
				array('bootstrap/jquery.flot.stack.js'),
				array('bootstrap/jquery.flot.resize.min.js'),

				array('bootstrap/jquery.chosen.min.js'),
				array('bootstrap/jquery.uniform.min.js'),
				array('bootstrap/jquery.colorbox.min.js'),
				array('bootstrap/jquery.cleditor.min.js'),
				array('bootstrap/jquery.noty.js'),
				array('bootstrap/jquery.elfinder.min.js'),
				array('bootstrap/jquery.raty.min.js'),
				array('bootstrap/jquery.iphone.toggle.js'),
				array('bootstrap/jquery.autogrow-textarea.js'),
				array('bootstrap/jquery.uploadify-3.1.min.js'),
				array('bootstrap/jquery.history.js'),
				array('bootstrap/charisma.js'),
		));

		$this->load->model("empleados_model");
		if($this->empleados_model->checkSession()){
			// $this->empleados_model->excepcion_privilegio = $this->excepcion_privilegio;
			// $this->info_empleado = $this->empleados_model->getInfoEmpleado($_SESSION['id_empleado'], true);
			$this->{$method}();
		}else
			$this->{'login'}();
	}

	public function index(){


		$params['info_empleado'] = $this->info_empleado['info']; //info empleado
		$params['seo'] = array(
			'titulo' => 'Panel de Administración'
		);


		$params['usuarios'] = $this->db->query("SELECT
			(SELECT Count(*) FROM usuarios WHERE status = 1) AS total,
			(SELECT Count(*) FROM usuarios WHERE status = 1 AND fecha_registro = '".date("Y-m-d")."') AS hoy,
			(SELECT Count(*) FROM (SELECT u.id_usuario FROM usuarios AS u INNER JOIN paquetes AS p ON u.id_usuario = p.id_usuario
				WHERE u.status = 1 AND p.status = 1 AND Date(p.fecha_vencimiento) >= Date(Now()) GROUP BY u.id_usuario) AS t1) AS tic_total,
			(SELECT Count(*) FROM (SELECT u.id_usuario FROM usuarios AS u INNER JOIN paquetes AS p ON u.id_usuario = p.id_usuario
				WHERE u.status = 1 AND p.status = 1 AND Date(p.fecha_vencimiento) >= Date(Now()) AND Date(p.fecha_creacion) = Date(Now())
				GROUP BY u.id_usuario) AS t1) AS tic_hoy")->row();


		$params['ventas'] = $this->db->query("SELECT
			(SELECT IFNULL(Sum(costo), 0) FROM paquetes WHERE status = 1
				AND Date(fecha_creacion) BETWEEN '".date("Y-m")."-01' AND '".date("Y-m-d")."') AS venta_mes,
			(SELECT IFNULL(Sum(costo), 0) FROM paquetes WHERE status = 1
				AND Date(fecha_creacion) = '".date("Y-m-d")."') AS venta_hoy")->row();

		$_GET['fstatus'] = '0';
		$this->load->model('ventas_model');
		$params['lista_ventas'] = $this->ventas_model->get_ventas();

		//Paquetes Proximos a vencer
		$params['paquetes_vencen'] = $this->db->query("SELECT p.id_paquete AS folio, u.id_usuario,
					u.nombre, Date(p.fecha_creacion) AS fecha_creacion,
					Date(p.fecha_vencimiento) AS fecha_vencimiento, (TO_DAYS(Date(p.fecha_vencimiento)) - TO_DAYS(Date(Now()))) AS dias,
					p.costo,
					IF(p.tipo='todo', 'ilimitado', 'individual') AS tipo, p.meses, p.status
				FROM paquetes AS p
					INNER JOIN usuarios AS u ON p.id_usuario = u.id_usuario
				WHERE u.status = 1 AND (TO_DAYS(Date(p.fecha_vencimiento)) - TO_DAYS(Date(Now()))) <= 15
				ORDER BY p.id_paquete ASC")->result();

		//Ultimos articulos vistos
		$params['articulos_vistos'] = $this->db->query("SELECT * FROM
				(SELECT a.numero, a.titulo, at.nombre, av.fecha FROM articulos AS a
					INNER JOIN articulos_visitas AS av ON a.id_articulo = av.id_articulo
					INNER JOIN articulos_tipo AS at ON at.id_tipo = a.id_tipo
				ORDER BY av.fecha DESC) AS t
			GROUP BY t.numero
			ORDER BY t.fecha DESC
			LIMIT 20")->result();

		//mensajes no leidos
		$params['mensajes'] = $this->db->query("SELECT (SELECT Count(*) FROM inbox WHERE alerta = 1) AS msgs, 
			(SELECT Count(*) FROM inbox WHERE alerta = 1 AND Date(fecha) = Date(Now())) AS msgs_hoy")->row();
		$this->load->model('mensajes_model');
    $params['conversaciones'] = $this->mensajes_model->get_conversaciones(true, '10');


		$this->load->view('panel/header', $params);
		$this->load->view('panel/general/menu', $params);
		$this->load->view('panel/general/home', $params);
		$this->load->view('panel/footer');
	}


	/**
	 * Genera el reporte productos bajos del stock
	 */
	public function productos_bajos(){
		$prod_bajos = $this->db->query("SELECT * FROM reportes_costo_existencias1 WHERE stock_min > existencia")->result();

		$this->load->library('mypdf');
		// Creación del objeto de la clase heredada
		$pdf = new MYpdf('P', 'mm', 'Letter');
		$pdf->show_head = true;
		$pdf->titulo2 = 'Reporte Productos Bajos de Inventario';
		$pdf->AliasNbPages();
		$pdf->AddPage();

		$links = array('', '', '', '');
		$aligns = array('C', 'C', 'C', 'C');
		$widths1 = array(98, 35, 35, 35);
		$header1 = array('Producto', 'Existencia', 'Stock min', 'Faltante');

		foreach($prod_bajos as $key => $item){
			if($pdf->GetY() >= $pdf->limiteY || $key == 0){ //salta de pagina si exede el max
				if($key > 0)
					$pdf->AddPage();

				$pdf->SetFont('Arial', 'B', 8);
				$pdf->SetTextColor(255, 255, 255);
				$pdf->SetFillColor(160, 160, 160);
				$pdf->SetX(6);
				$pdf->SetAligns($aligns);
				$pdf->SetWidths($widths1);
				$pdf->Row($header1, true);
			}

			$pdf->SetFont('Arial', '', 8);
			$pdf->SetTextColor(0,0,0);

			$datarow = array($item->nombre,
					$item->existencia,
					$item->stock_min,
					$item->stock_min - $item->existencia
			);

			$pdf->SetX(6);
			$pdf->SetAligns($aligns);
			$pdf->SetWidths($widths1);
			$pdf->Row($datarow, false);
		}

		$pdf->Output('reporte.pdf', 'I');
	}

	/**
	 * Pospone las alertas unos dias mas
	 */
	public function posponer(){
		if(isset($_GET['del']{0})){ //elimina la alerta
			$this->db->delete('alertas', "tabla_obj = '".$_GET['tblo']."' AND id_obj = '".$_GET['ido']."'");
		}else{ //pospone la alerta
			$this->db->set('fecha_vencimiento', '( now() + \'3 days\'::interval )', false);
			$this->db->where("tabla_obj = '".$_GET['tblo']."' AND id_obj = '".$_GET['ido']."'");
			$this->db->update("alertas");
		}

		header("Location: ".base_url('panel/home/'));
	}




	/**
	 * carga el login para entrar al panel
	 */
	public function login(){
		$this->carabiner->css(array(
				array('general/forms.css', 'screen')
		));

		$params['seo'] = array(
			'titulo' => 'Login'
		);

		$this->load->library('form_validation');
		$rules = array(
			array('field'	=> 'usuario',
				'label'		=> 'Usuario',
				'rules'		=> 'required'),
			array('field'	=> 'pass',
				'label'		=> 'Contraseña',
				'rules'		=> 'required')
		);
		$this->form_validation->set_rules($rules);
		if($this->form_validation->run() == FALSE){
			$params['frm_errors'] = array(
					'title' => 'Error al Iniciar Sesión!',
					'msg' => preg_replace("[\n|\r|\n\r]", '', validation_errors()),
					'ico' => 'error');
		}else{
			// $respons = $this->empleados_model->login();
			// if($respons[0])
			// 	redirect(base_url('panel/home'));
			$this->load->model('usuarios_model');
			// $data    = array('usuario'=>$this->input->post('usuario'), 'pass'=>$this->input->post('pass'));
			$data = "(email='".$this->input->post('usuario')."' OR usuario='".$this->input->post('usuario')."') AND pass='".$this->input->post('pass')."' AND status='1' ";
			$mdl_res = $this->usuarios_model->setLogin($data);
			if ($mdl_res[0] && $this->empleados_model->checkSession()) {
				redirect(base_url('panel/home'));
			}
			else{
				$params['frm_errors'] = array(
					'title' => 'Error al Iniciar Sesión!',
					'msg' => 'El usuario y/o contraseña son incorrectos, o no cuenta con los permisos necesarios para loguearse',
					'ico' => 'error');
			}
		}

		$this->load->view('panel/header', $params);
		$this->load->view('panel/general/login', $params);
		$this->load->view('panel/footer');
	}

	/**
	 * cierra la sesion del usuario
	 */
	public function logout(){
		$this->session->sess_destroy();
		redirect(base_url('panel/home'));
	}
}

